package com.coding.kan_yi_dao.interceptor;

import cn.hutool.core.util.StrUtil;

import com.alibaba.fastjson.JSON;
import com.coding.kan_yi_dao.entity.User;
import com.coding.kan_yi_dao.util.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class RefreshTokenExpireInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1、获取token
        String token = request.getHeader("X-Token");
        // 2、判断token是否为空
        if(StrUtil.isBlank(token)){
            return true;
        }
        // 3、redis获取用户信息
        String key = "login:user:" + token;
        String userJson = redisTemplate.opsForValue().get(key);
        if(StrUtil.isBlank(userJson)){
            return true;
        }
        // 4、将json字符串转换为User对象
        User user = JSON.parseObject(userJson, User.class);
        // 5、用户信息传递给下一个控制器
        UserHolder.set(user);
        // 6、刷新token有效期
        redisTemplate.expire(key,30L, TimeUnit.MINUTES);
        // 7、放行
        return true;
    }
}
